﻿using UnityEngine;
using System.Collections;
using System.Threading;

namespace ZSW.Framework.Sync
{
    public class ZSWF_SyncHandler : ZSWF_Singleton<ZSWF_SyncHandler>
    {
        private bool m_isExited = false;
        private object m_guard = new Object();
        private Queue m_queue = new Queue();
        private int m_mainThreadId = 0;

        public ZSWF_SyncHandler()
        {
            m_mainThreadId = Thread.CurrentThread.ManagedThreadId;
        }

        void Update()
        {
            while (m_queue.Count > 0)
            {
                HandleMethod();
            }
        }

        void OnDestroy()
        {
            m_isExited = true;
        }

        public void Synchronize(ZSWF_Object.ZSWMethod method)
        {
            if (m_isExited)
            {
                return;
            }
            if (Thread.CurrentThread.ManagedThreadId != m_mainThreadId)
            {
                lock (m_guard)
                {
                    m_queue.Enqueue(method);
                }
            }
            else
            {
                method();
            }
        }
        private void HandleMethod()
        {
            ZSWF_Object.ZSWMethod method = null;
            lock (m_guard)
            {
                if (m_queue.Count > 0)
                    method = (ZSWF_Object.ZSWMethod)m_queue.Dequeue();
            }
            if (method != null)
            {
                method();
            }
        }
    }
}